package interview.thread;

/**
 * wait和sleep的区别
 * @Author: cctv
 * @Date: 2019/5/17 11:49
 */
public class WaitSleepDemo {
    public static void main(String[] args) {
        final Object lock = new Object();
        new Thread(() -> {
            System.out.println("thread A is waiting to get lock");
            synchronized (lock) {
                try {
                    System.out.println("thread A get lock");
                    // 先等B运行起来再到下一步
                    Thread.sleep(20);
                    System.out.println("thread A do wait method");
                    // wait让出CPU和锁 B会抢到锁执行B后再执行A
//                    lock.wait(1000);
                    // 无限等待状态
                    lock.wait();

                    // sleep不会让出锁 A执行完了之后再执行B
//                    Thread.sleep(1000);
                    System.out.println("thread A is done");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 先启动A拿到锁，再让B也运行
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            System.out.println("thread B is waiting to get lock");
            synchronized (lock) {
                try {
                    System.out.println("thread B get lock");
                    System.out.println("thread B do wait method");
                    Thread.sleep(10);
                    System.out.println("thread B is done");
                    lock.notify();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
